<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Symfony\Component\HttpFoundation\Request;
use Validator;
use Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //dump(bcrypt('123456'));die;
        $this->middleware('guest', ['except' => 'logout']);
    }

    //重写 LOGIN 方法
    public function login(Request $request)
    {
        //密码生成方法 bcrypt('123456')
        $data = $request->all();

        $phone = $request->get('phone','');
        $password = $request->get('password','');

        $rules = ['captcha' => 'required|captcha'];
        $validator = Validator::make($data, $rules);

        if ($validator->fails()){
            return redirect('login')->withInput($request->except('password'))->withErrors('图片验证码错误');
        }

        if (Auth::attempt(['phone'=>$phone,'password'=>$password])){
            return redirect('/');
        } else {
            return redirect('login')->withInput($request->except('password'))->withErrors('用户或用户名或密码错误');
        }
    }

    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }
}
